package com.zty.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * @Author ZTY
 * @Description
 * @Date 15:34 2023-12-25
 **/

@Configuration
public class RestTemplateConfig {

    private final RestTemplateErrorHandler restTemplateErrorHandler;
    private final RestTemplateLoggingInterceptor restTemplateLoggingInterceptor;

    public RestTemplateConfig(RestTemplateErrorHandler restTemplateErrorHandler, RestTemplateLoggingInterceptor restTemplateLoggingInterceptor) {
        this.restTemplateErrorHandler = restTemplateErrorHandler;
        this.restTemplateLoggingInterceptor = restTemplateLoggingInterceptor;
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder,
                                     ClientHttpRequestFactory httpRequestFactory){

        RestTemplate restTemplate = builder.build();

        //  配置日志信息（要将请求信息打印出来）
        //  可以通过设置一个拦截器，打印出将执行前后的信息，就为完整的日志信息

        //  该拦截器只能拦截到成功的请求
        restTemplate.setInterceptors(Collections.singletonList(restTemplateLoggingInterceptor));
        //  失败的请求要对其独立设置异常处理器
        restTemplate.setErrorHandler(restTemplateErrorHandler);
        restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(httpRequestFactory));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(){
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(150000);
        simpleClientHttpRequestFactory.setReadTimeout(15000);
        return simpleClientHttpRequestFactory;
    }
}
